//
//  ZCLoadingDetailViewController.m
//  ZhiChe-Wms
//
//  Created by 高睿婕 on 2018/9/7.
//  Copyright © 2018年 Regina. All rights reserved.
//

#import "ZCLoadingDetailViewController.h"
#import "ZCTaskTotalNumTableViewCell.h"
#import "ZCLoadingModel.h"
#import "ZCAbnormalSignViewController.h"


static NSString *loadingDetailCellID = @"ZCTaskTotalNumTableViewCell";

@interface ZCLoadingDetailViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIView *handleView;
@property (nonatomic, strong) UIButton *abnormalButton;
@property (nonatomic, strong) UIButton *commitButton;
@property (nonatomic, strong) ZCLoadingInfoModel *detailModel;
@property (nonatomic, strong) MBProgressHUD *hud;

@end

@implementation ZCLoadingDetailViewController
#pragma mark - 懒加载
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, space(90 * 7) + 64) style:UITableViewStylePlain];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.scrollEnabled = NO;
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            _tableView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0);
            _tableView.scrollIndicatorInsets = _tableView.contentInset;
            _tableView.estimatedRowHeight = 0;
            _tableView.estimatedSectionFooterHeight = 0;
            _tableView.estimatedSectionHeaderHeight = 0;
        }
        [_tableView registerClass:[ZCTaskTotalNumTableViewCell class] forCellReuseIdentifier:loadingDetailCellID];
    }
    return _tableView;
}

- (UIView *)handleView {
    if (!_handleView) {
        _handleView = [[UIView alloc] init];
        _handleView.backgroundColor = [UIColor whiteColor];
    }
    return _handleView;
}

- (UIButton *)abnormalButton {
    if (!_abnormalButton) {
        _abnormalButton = [[UIButton alloc] init];
        [_abnormalButton setTitle:@"异常登记" forState:UIControlStateNormal];
        [_abnormalButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_abnormalButton setBackgroundColor:ZCColor(0xff6112, 1)];
        _abnormalButton.layer.masksToBounds = YES;
        _abnormalButton.layer.cornerRadius = space(6);
        [_abnormalButton addTarget:self action:@selector(abnormalButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _abnormalButton;
}

- (UIButton *)commitButton {
    if (!_commitButton) {
        _commitButton = [[UIButton alloc] init];
        [_commitButton setTitle:@"确认交验" forState:UIControlStateNormal];
        [_commitButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_commitButton setBackgroundColor:ZCColor(0xff6112, 1)];
        _commitButton.layer.masksToBounds = YES;
        _commitButton.layer.cornerRadius = space(6);
        [_commitButton addTarget:self action:@selector(commitButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        _commitButton.timeInterval = 3;
    }
    return _commitButton;
}

#pragma mark - 生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"装车交验";
    UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 30)];
    [backButton setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(backButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.handleView];
    [self.handleView addSubview:self.abnormalButton];
    [self.handleView addSubview:self.commitButton];
    [self updateViewConstraints];
    self.hud = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:self.hud];
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.hud showAnimated:YES];
    [self loadData];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.hud hideAnimated:YES];
    self.hud.mode = MBProgressHUDModeIndeterminate;
    
}

#pragma mark - 网络请求
- (void)loadData {
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setObject:self.keyId forKey:@"condition[key]"];
    [param setObject:self.visitType forKey:@"condition[visitType]"];

    [self.hud showAnimated:YES];
    __weak typeof(self)weakSelf = self;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [ZCHttpTool postWithURL:LoadingDetail params:param success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if ([responseObject[@"code"] integerValue] == 0) {
                [weakSelf.hud hideAnimated:YES];
                weakSelf.detailModel = [ZCLoadingInfoModel yy_modelWithDictionary:responseObject[@"data"]];
                [weakSelf.tableView reloadData];
                weakSelf.handleView.hidden = [weakSelf.detailModel.status isEqualToString:@"BS_CREATED"] ? NO : YES;
            }else {
                weakSelf.hud.mode = MBProgressHUDModeText;
                weakSelf.hud.label.text = responseObject[@"message"];
                [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
            }
        } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
            weakSelf.hud.mode = MBProgressHUDModeText;
            weakSelf.hud.label.text = error.localizedDescription;
            [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
        }];
    });
}

#pragma mark - 按钮点击
- (void)backButtonClick:(UIButton *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)abnormalButtonClick:(UIButton *)sender {
    ZCAbnormalSignViewController *signVC = [[ZCAbnormalSignViewController alloc] init];
    signVC.releaseId = self.detailModel.Id;
    signVC.taskType = @"60";
    signVC.visitType = @"CLICK";
    signVC.orderNoAlloc = self.detailModel.cusOrderNo;
    signVC.vinAlloc = self.detailModel.vin;
    signVC.vehicleAlloc = self.detailModel.cusVehicleType;
    signVC.isCanSend = self.detailModel.isCanSend;
    [self.navigationController pushViewController:signVC animated:YES];
}

- (void)commitButtonClick:(UIButton *)sender {
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setObject:self.detailModel.Id forKey:@"condition[key]"];

    [self.hud showAnimated:YES];
    __weak typeof(self)weakSelf = self;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [ZCHttpTool postWithURL:LoadingCommit params:param success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if ([responseObject[@"code"] integerValue] == 0) {
                [weakSelf.hud hideAnimated:YES];
                weakSelf.detailModel = [ZCLoadingInfoModel yy_modelWithDictionary:responseObject[@"data"]];
                [weakSelf.tableView reloadData];
                weakSelf.handleView.hidden = [weakSelf.detailModel.status isEqualToString:@"BS_CREATED"] ? NO : YES;
            }else {
                weakSelf.hud.mode = MBProgressHUDModeText;
                weakSelf.hud.label.text = responseObject[@"message"];
                [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
            }
        } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
            weakSelf.hud.mode = MBProgressHUDModeText;
            weakSelf.hud.label.text = error.localizedDescription;
            [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
        }];
    });
}

#pragma mark - UITableviewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 7;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ZCTaskTotalNumTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:loadingDetailCellID forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (indexPath.row == 0) {
        cell.title = @"指令号";
        cell.content = self.detailModel.shipmentGid;
    }else if (indexPath.row == 1) {
        cell.title = @"订单号";
        cell.content = self.detailModel.cusOrderNo;
    }else if (indexPath.row == 2) {
        cell.title = @"车架号";
        cell.content = self.detailModel.vin;
    }else if (indexPath.row == 3) {
        cell.title = @"起运地";
        cell.content = self.detailModel.originLocationName;
    }else if (indexPath.row == 4) {
        cell.title = @"目的地";
        cell.content = self.detailModel.destLocationName;
    }else if (indexPath.row == 5) {
        cell.title = @"指令时间";
        cell.content = self.detailModel.gmtModified;
    }else if (indexPath.row == 6) {
        cell.title = @"状态";
        cell.content = [self.detailModel.status isEqualToString:@"BS_CREATED"] ? @"已调度" : @"已交验";
        cell.contentColor = ZCColor(0xff8213, 1);
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return space(90);
}



#pragma mark - 布局
- (void)updateViewConstraints {
    [super updateViewConstraints];
    __weak typeof(self)weakSelf = self;
    [_handleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.view.mas_left);
        make.right.equalTo(weakSelf.view.mas_right);
        make.bottom.equalTo(weakSelf.view.mas_bottom);
        make.top.equalTo(weakSelf.tableView.mas_bottom);
    }];
    
    [_abnormalButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(weakSelf.handleView.mas_centerY);
        make.left.equalTo(weakSelf.handleView.mas_left).offset(space(80));
        make.right.equalTo(weakSelf.handleView.mas_centerX).offset(-space(40));
        make.height.mas_equalTo(space(90));
    }];
    
    [_commitButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(weakSelf.abnormalButton.mas_centerY);
        make.left.equalTo(weakSelf.handleView.mas_centerX).offset(space(40));
        make.right.equalTo(weakSelf.handleView.mas_right).offset(-space(80));
        make.height.equalTo(weakSelf.abnormalButton.mas_height);
    }];
    
}


@end
